package com.blueocean_health.care.management.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.blueocean_health.care.management.common.base.id.IdUtils;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.domain.base.SysResult;
import com.blueocean_health.care.management.service.UploadService;
import com.blueocean_health.care.management.util.PicUtils;

/**
* @author huyanqiu
* @date 2018年6月26日 下午3:04:31
* @version 版本号：1.0
*/
@Service
public class UploadServiceImpl implements UploadService {
	
	// 医院图片存储路径
	@Value("${picture.filePath.hospitalpic}")
	private String picturepathHospitalpic;
	// 医院图片存储路径
	@Value("${service.address.hospitalpic}")
	private String serviceAddressHospitalpic;
	
	// 图片存储路径
	private String picturepath;
	// 图片访问路径
	@SuppressWarnings("unused")
	private String serviceAddress;

	/**
	 * 上传图片
	 * @param imgFile 上传图片
	 * @param pictype 1：医院图片 。。。。。。
	 */
	@Override
	public SysResult upload(MultipartFile imgFile, String pictype) throws Exception {
		switch (pictype) {
		case "1":
			picturepath = picturepathHospitalpic;
			break;

		default:
			break;
		}
		// 服务器存储路径
		String pictureName ="";
		try {
			String errorMsg = "";
			if (imgFile.isEmpty()) {
				errorMsg = "上传参数有误，请重新上传。";
			} else {
				String filename = imgFile.getOriginalFilename();
				String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
				if (!".png".equals(extName) && !".jpg".equals(extName) && !".jpeg".equals(extName)) {
					errorMsg = "上传图片只能是PNG或JPG格式";
				}
				if (!StringUtils.isEmpty(errorMsg)) {
					return SysResult.error(errorMsg);
				}
				File file = new File(picturepath);
				if (!file.exists()) {
					file.mkdirs();
				}
				pictureName = IdUtils.getRandomIdByMillis() + extName;
				File dest = new File(picturepath + pictureName);
				imgFile.transferTo(dest);
				PicUtils.commpressPicForScale(picturepath + pictureName, picturepath + pictureName, 2048, 0.8);
				//   Thumbnails.of(dest).scale(1f).outputQuality(0.25f).toFile(dest);
				if (dest.exists()) {
					Map<String, String> hashMap = new HashMap<String,String>();
					hashMap.put("url", serviceAddressHospitalpic+pictureName);
					return SysResult.ok("图片上传成功", hashMap);
				}else{
					return null;
				}
			}
		} catch (Exception e) {
			throw new Exception(); // 前端上传图片只有抛出异常才能显示上传失败
		}
		return null;
	}

}
